<template>
  <view class="chat-input-box">
    <view
      class="chat-input-box__ctx">
      <image
        @click="clickSpeech"
        class="chat-input-btn"
        :src="!speechMode ? '../static/icon_btn_speech.png'
                          : '../static/icon_btn_keyboard.png'"
      ></image>
      <input
        v-if="!speechMode"
        ref="input"
        class="chat-input-this"
        v-model="text"
        type="text"
        :focus="focus"
        @blur="focus = false"
        @focus="onInputFocus"
      />
      <view
        v-else
        @touchstart.prevent="touchOnSpeech"
        @touchend="touchOffSpeech"
        @touchmove="touchMoveSpeech"
        class="chat-input-this chat-input-speech-btn"
      >按住说话</view>
      <image
        class="chat-input-btn"
        src="../static/icon_btn_face.png"
        @click="clickFaceBtn"
      ></image>
      <image
        v-if="!text"
        class="chat-input-btn"
        src="../static/icon_btn_more.png"
        @click="clickExtra"
      ></image>
      <view
        v-else
        class="chat-send-btn"
        @click="clickSend"
      >
        发送
      </view>
    </view>
    <view class="chat-input-box__drawer">
      <drawer-face
        v-if="faceMode"
        @emoji="text += $event"
      ></drawer-face>
      <drawer-extra
        v-if="extraMode"
        @click-fn="onClickExtraFn"
      ></drawer-extra>
    </view>
<!--    这里比较特别，是针对覆盖层的-->
    <view v-if="speechIng" class="speech-fixed">
      <view></view>
      <view
        class="speech-fixed__time"
      >
        {{ (speechIng.time / 1000).toFixed(0) }}
      </view>
      <view
        class="speech-fixed__bottom"
        :class="{
          'active': hoverOnSpeechCancelBtn
        }"
      >
        <image
          class="speech-fixed__bottom-remove"
          src="../static/icon_close_white.png"
        ></image>
      </view>
    </view>
  </view>
</template>

<script>
  import _ from 'lodash'
  import drawerFace from './ChatInputDrawer/face'
  import drawerExtra from './ChatInputDrawer/extra'
  export default {
    components: {
      drawerFace,
      drawerExtra
    },
    data () {
			let sysInfo = uni.getSystemInfoSync()
      return {
				pageHeight: sysInfo.windowHeight,
        text: '',
        focus: false,
        speechMode: false,
        faceMode: false,
        extraMode: false,
        speechIng: false,
        hoverOnSpeechCancelBtn: false
      }
    },
    mounted () {
      this.mounted = true
    },
    beforeDestroy() {
      this.$imUtils.endRecord()
    },
    methods: {
      async inputFocus () {
        await this.$next()
        this.focus = true
        this.speechMode = false
        this.faceMode = false
        this.extraMode = false
      },
      async clearAllMode (keepFocus) {
        this.speechMode = false
        this.faceMode = false
        this.extraMode = false
        if (!keepFocus) {
          uni.hideKeyboard()
          this.focus = false
        }
        await this.$next()
      },
      async onInputFocus () {
        if (this.speechMode || this.faceMode || this.extraMode) {
          await this.clearAllMode()
          await this.$delay(100)
          this.inputFocus()
        }
      },
      async clickFaceBtn () {
        let onMode = this.faceMode * 1
        await this.clearAllMode()
        this.faceMode = !onMode
        !this.faceMode && this.inputFocus()
      },
      async clickSpeech () {
        let onMode = this.speechMode * 1
        await this.clearAllMode()
        this.speechMode = !onMode
        !this.speechMode && this.inputFocus()
        if (this.speechMode) {
          this.$imUtils.touchRecordPermission()
        }
      },
      async clickExtra () {
        let onMode = this.extraMode * 1
        await this.clearAllMode()
        this.extraMode = !onMode
        !this.extraMode && this.inputFocus()
      },
      clickSend () {
        this.$emit('send-text', this.text + '')
        this.text = ''
      },
      async touchOnSpeech () {
        this.speechIng = { time: 0, timer: null }
        this.speechIng.timer = setInterval(e => {
          this.speechIng && (this.speechIng.time += 500);
          if (this.speechIng.time >= 6000) {
            this.touchOffSpeech()
          }
        }, 500)
        console.log('speech-start')
        let success = await this.$imUtils.startRecord()
        if (!success) {
          this.touchOffSpeech()
          uni.showToast({
            icon: 'none',
            position: 'bottom',
            title: '录音失败，请检查是否授权麦克风权限'
          })
        }
      },
      touchOffSpeech: _.debounce(async function () {
        if (!this.speechIng) {
          return
        }
        clearInterval(this.speechIng.timer)
        let timeLen = this.speechIng.time
        this.speechIng = null
        if (this.hoverOnSpeechCancelBtn) {
          this.hoverOnSpeechCancelBtn = false
          return
        }
        if (timeLen < 1000) {
          return
        }
        let filePath = await this.$imUtils.endRecord()
        if (!filePath) {
          return
        }
        this.$emit('send-audio', { filePath, timeLen })
      }, 500, { leading: true, trailing: false }),
      touchMoveSpeech ({ touches }) {
        touches = touches[0]
        let minScope = this.pageHeight - 50 - 100
        let maxScope = this.pageHeight - 50
        if (touches.pageY >= minScope && touches.pageY <= maxScope) {
          this.hoverOnSpeechCancelBtn = true
        } else {
          this.hoverOnSpeechCancelBtn = false
        }
      },
      onClickExtraFn: _.debounce(async function ({ name }) {
        let ret = null
        switch (name) {
          case 'image':
            ret = await this.$imUtils.openAlbumBridge()
            if (ret.length === 0) {
              return
            }
            let isVideo = ret[0].indexOf(',') >= 0
            if (ret.length === 1 && isVideo) {
              // TODO: 缺少时间和封面图
              ret = ret[0].split(',')
              this.$emit('send-video', { filePath: ret[0], type: 'mp4', timeLen: 1, snapshotPath: ret[1] || '' })
              return
            }
            this.$emit('send-image', { filePaths: ret })
          break;
          case 'camera':
            uni.showActionSheet({
              itemList: ['拍照', '录像'],
              success: async e => {
                let options = [
                  { quality: 0.5, imageHeight: 640 },
                  { quality: 0.5 }
                ][e.tapIndex]
                let type = [
                  this.$imUtils.CAMERA_TYPE_TAKE_PHOTO,
                  this.$imUtils.CAMERA_TYPE_RECORD
                ][e.tapIndex]
                if (type && options) {
                  let ret = await this.$imUtils.openCamera(type, options)
                  if (typeof ret === 'string') {
                    ret = { data: ret }
                  }
                  if (ret.data) {
                    let isVideo = ret.data.indexOf(',') >= 0
                    if (isVideo) {
                      ret.data = ret.data.split(',')
                      this.$emit('send-video', {
                        filePath: ret.data[0],
                        type: 'mp4',
                        timeLen: 1,
                        snapshotPath: ret.data[1] || ''
                      })
                    } else {
                      this.$emit('send-image', {
                        filePaths: [ret.data]
                      })
                    }
                  }
                }
              }
            })
          break;
          case 'location':
            let { longitude, latitude, address } = await this.$imUtils.chooseLocation()
            this.$emit('send-location', { longitude, latitude, address })
          break;
          case 'voip':
            await this.$txcalling.checkPermissions()
            uni.showActionSheet({
              itemList: ['语音通话', '视频对话'],
              success: async e => {
                let eventType = [
                  'voip-audio',
                  'voip-video'
                ][e.tapIndex]
                eventType && this.$emit(eventType)
              }
            })
          break;
          default:
            console.log(name)
          break
        }
      }, 500, { leading: true, trailing: false })
    }
  }
</script>

<style lang="scss" scoped>
  @import "./common";
  .chat-input-box {
    border-top: 1px solid $br-solid-color;
    .chat-input-box__ctx {
      @extend .flex;
      padding: 0 10px;
      height: 55px;
      justify-content: space-between;
      & > * + * {
        margin-left: 10px;
      }
      .chat-input-btn {
        @extend .flex-shrink;
        height: 26px;
        width: 26px;
      }
      .chat-input-this {
        @extend .flex-grow;
        height: 38px;
        padding: 0 10px;
        background-color: $c-white;
        border-radius: $br-radius;
      }
      .chat-input-speech-btn {
        @extend .flex;
        &:active {
          background-color: #e6e6e6;
        }
      }
      .chat-send-btn {
        @extend .flex;
        width: 58px;
        height: 30px;
        font-size: $fz-default;
        color: $c-white;
        background-color: #5EC96F;
        border-radius: $br-radius;
        &:active {
          opacity: 0.8;
        }
      }
    }
  }

  .speech-fixed {
    @extend .flex;
    flex-direction: column;
    justify-content: space-between;
    position: fixed;
    top: 0;
    bottom: 55px;
    left: 0;
    right: 0;
    background-color: rgba(0,0,0,0.5);
    overflow: hidden;
    .speech-fixed__time {
      @extend .flex;
      width: 100px;
      height: 100px;
      color: $c-white;
      font-weight: bold;
      font-size: 40px;
      border-radius: $br-radius;
      background-color: rgba($c-black, 0.3);
    }
    .speech-fixed__bottom {
      @extend .flex;
      height: 100px;
			width: 100%;
			background-image: url(../static/bg_speech_remove.png);
			background-size: 100% 100%;
      &.active {
        background-image: url(../static/bg_speech_remove_active.png);
      }
      .speech-fixed__bottom-remove {
        width: 30px;
        height: 30px;
      }
    }
  }
</style>
